//
//  TrainTicketHomeController.swift
//  AirTravel
//
//  Created by apple on 2021/8/9.
//

import UIKit
import JXBanner
import JXPageControl
import FWPopupView
import Moya
import SwiftyJSON
import MapKit
import CoreLocation
class TrainTicketHomeController: UIViewController {

    @IBOutlet weak var topLine: NSLayoutConstraint!
    @IBOutlet weak var tabView: UITableView!
    let identifyTTB = "TrainTicketBannerCell"
    let identifyCRS = "CarRentalServiceCell"
    let identifyPC = "Pure1Cell"
    let identifyHH = "HotelHeaderView"
    
    var dataStr = ""
    var according = ""
    var difference = "今天"
    var currCity = ""
    var startCity = "成都"
    var endCity = "北京"
    
    var is_students = 0
    var is_railway = 0
    
    
    var time1 = ""
    var time2 = ""
    
    var page = 1
    
    var cityId = ""
    
    let locationManager = CLLocationManager()
    
    var dataSouce = [NSDictionary]()
    var mutDataDic = Dictionary<Int, NSArray>()
    
    lazy var banner: JXBanner = {
        let banner = JXBanner()
        banner.placeholderImgView.image = UIImage(named: "banner_placeholder")
        banner.delegate = self
        banner.tag = 0
        banner.dataSource = self
        banner.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 203)
        return banner
    }()
    
    lazy var radioTimeView: RadioTimeView = {
        let customPopupView = RadioTimeView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 450))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    lazy var guessLikeView: HomeGuessLikeModel = {
        let iconView = HomeGuessLikeModel()
        iconView.delegate = self
        iconView .setUpdata(array: [])
        return iconView
    }()
    
    lazy var switchAddressView: SwitchAddressView = {
        let customPopupView = SwitchAddressView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT * 0.6))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.clear
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "1"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(gotoHotel(dic:)), name: Notification.Name("GOTOHOTEL"), object: nil)
        if SCREEN_HEIGHT >= 812 {
            self.topLine.constant = 88
        }else{
            self.topLine.constant = 64
        }
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "TrainTicketBannerCell", bundle: nil), forCellReuseIdentifier: identifyTTB)
        self.tabView.register(UINib.init(nibName: "CarRentalServiceCell", bundle: nil), forCellReuseIdentifier: identifyCRS)
        self.tabView.register(UINib.init(nibName: "Pure1Cell", bundle: nil), forCellReuseIdentifier: identifyPC)
        self.tabView.register(UINib.init(nibName: "HotelHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: identifyHH)
        self.tabView.separatorStyle = .none
        if #available(iOS 11.0, *) {
            self.tabView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = true
        }
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM月dd日"
        self.according = dateFormatter.string(from: Date())
        dateFormatter.dateFormat = "yyyy-MM-dd"
        self.dataStr = dateFormatter.string(from: Date())
        
        
        
        //获取日期格式化对象
       
        dateFormatter.dateFormat="yyyy-MM-dd"
        self.time1 = dateFormatter.string(from: Date())
        let calendar = Calendar.current
        let date1 = calendar.date(byAdding: .day, value: 1, to: Date())!
        self.time2 = dateFormatter.string(from: date1)
     
        
        self.tabView.es.addPullToRefresh {[weak self] in
            self?.page = 1
            self?.searchHotelList()
        }
        
        self.tabView.es.addInfiniteScrolling {[weak self] in
            self?.page += 1
            self?.searchHotelList()
        }
        
        locationStart()
        
    }
    
    @objc func gotoHotel(dic:Notification){
        
        let data = dic.object as! Dictionary<String, Any>
        
        
            let vc = HotelDetailsController()
            vc.time2 = time2
            vc.time1 = time1
            vc.cityId = cityId
        
        print("\(data)")

        vc.hotelId = "\(data["sourceHotelCode"] ?? "")"
            self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    
    func locationStart() {
        //判断是否允许定位
        if CLLocationManager.locationServicesEnabled() {
            self.locationManager.delegate = self
            //设置定位精度
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            //每隔多少米定位一次（这里的设置为每隔百米)
            self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters
            self.locationManager.requestWhenInUseAuthorization()
            //开始定位
            self.locationManager.startUpdatingLocation()
        }else{
            YProgressHUD.showToast("定位服务当前可能尚未打开，请设置打开！")
        }
    }

    @IBAction func backBtn(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    //获取酒店列表接口
    func searchHotelList() {
         NetWorkRequest(API1.searchHotelList(parameters: ["cityId":self.cityId,"checkInDate":self.time1,"checkOutDate":self.time2,"sortType":"1","pageIndex":self.page,"pageCount":"10"]), completion: {[weak self] (responseString) -> (Void) in
            let data = responseString["data"]["hotelList"].arrayObject
            self?.tabView.es.stopPullToRefresh()
            self?.tabView.es.stopLoadingMore()
            if let array = data {
                self?.mutDataDic.updateValue((array as NSArray?)!, forKey: self!.page)
                self?.dataSouce.removeAll()
                for item in 1...self!.page {
                    let ar = (self?.mutDataDic[item] ?? []) as NSArray
                    for item in ar {
                        self?.dataSouce.append(item as! NSDictionary)
                    }
                }
            }else{
                self?.mutDataDic.updateValue(([]), forKey: self!.page)
                self?.dataSouce.removeAll()
                for item in 1...self!.page {
                    let ar = (self?.mutDataDic[item] ?? []) as NSArray
                    for item in ar {
                        self?.dataSouce.append(item as! NSDictionary)
                    }
                }
            }
            self?.guessLikeView.setUpdata(array:self?.dataSouce ?? [])
            self?.tabView.reloadData()
        }, failed: {[weak self] (failedResutl) -> (Void) in
            self?.tabView.es.stopPullToRefresh()
            self?.tabView.es.stopLoadingMore()
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: {[weak self] () -> (Void) in
            self?.tabView.es.stopPullToRefresh()
            self?.tabView.es.stopLoadingMore()
            print("网络异常,超时")
        })
    }
    
}

extension TrainTicketHomeController:UITableViewDataSource,UITableViewDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int{
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyTTB) as! TrainTicketBannerCell
            cell.selectionStyle = .none
            cell.bannerView.addSubview(self.banner)
            cell.dateOfLab.addTarget(self, action: #selector(dateOf), for: .touchUpInside)
            cell.dateOfLab.setTitle(self.according, for: .normal)
            cell.tomorrowLab.text = self.difference
            cell.queryBTN.addTarget(self, action: #selector(query), for: .touchUpInside)
            cell.startBtn.setTitle(self.startCity, for: .normal)
            cell.endBtn.setTitle(self.endCity, for: .normal)
            cell.startBtn.addTarget(self, action: #selector(startAddress(sender:)), for: .touchUpInside)
            cell.endBtn.addTarget(self, action: #selector(endAddress(sender:)), for: .touchUpInside)
            cell.switchBtn.addTarget(self, action: #selector(switchBtn(sender:)), for: .touchUpInside)
            cell.studentsBtn.addTarget(self, action: #selector(students(sender:)), for: .touchUpInside)
            cell.railwayBtn.addTarget(self, action: #selector(railway(sender:)), for: .touchUpInside)
            
            cell.jpBUtton.addTarget(self, action: #selector(jpClick(sender:)), for: .touchUpInside)
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyCRS) as! CarRentalServiceCell
            cell.leftBt.addTarget(self, action: #selector(leftClick), for: .touchUpInside)
            cell.rightBt.addTarget(self, action: #selector(rightClick), for: .touchUpInside)
            cell.selectionStyle = .none
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyPC) as! Pure1Cell
            cell.selectionStyle = .none
            self.guessLikeView.bindViewToViewModel(collView: cell.collVIew)

            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.section {
        case 0:
            return 452
        case 1:
            return 100
        default:
            //            if let array = self.goodsList {
            let i = 12 / 2
            let j = 12 % 2
            //                if j > 0 {
            //                    j = 1
            //                }
            let h = CGFloat(((SCREEN_WIDTH - 40) / 2 + 120))
            let g = j + i
            return h * CGFloat(g) + 10.0
            //            }else{
            //                return 0
            //            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        switch section {
        case 2:
            return 50
        default:
            return 0
        }
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifyHH) as! HotelHeaderView
        switch section {
        case 2:
            headView.titleLab.text = "酒店推荐"
            headView.img.isHidden = true
            headView.leftLine.constant = 18
        default:
            headView.img.isHidden = true
            headView.titleLab.isHidden = true
        }
        return headView
    }
    
    @objc func dateOf() {
        self.radioTimeView.show()
    }
    //查询
    @objc func query() {
        let vc = ListTrainController()
        vc.according = self.according
        vc.difference = self.difference
        vc.dataStr = self.dataStr
        vc.fromStationName = self.startCity
        vc.toStationName = self.endCity
        vc.isStudent = self.is_students
        vc.isHigh = self.is_railway
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //开始
    @objc func startAddress(sender:UIButton) {
        self.switchAddressView.hcp_positioning(city: self.currCity, logoNumber: 0)
        self.switchAddressView.show()
    }
    //结束
    @objc func endAddress(sender:UIButton) {
        self.switchAddressView.hcp_positioning(city: self.currCity, logoNumber: 1)
        self.switchAddressView.show()
    }
    //交换
    @objc func switchBtn(sender:UIButton) {
        let str = self.startCity
        self.startCity = self.endCity
        self.endCity = str
    }
    //学生票
    @objc func students(sender:UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            self.is_students = 1
        }else{
            self.is_students = 0
        }
    }
    //高铁票
    @objc func railway(sender:UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            self.is_railway = 1
        }else{
            self.is_railway = 0
        }
    }
    
    @objc func jpClick(sender:UIButton) {
        let vc=AirplaneVC.init()
        let cvc=getCurrentVc()
        cvc.navigationController?.pushViewController(vc, animated: true)
     
    }
    
    @objc func leftClick() {
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OtherMainViewController") as! OtherMainViewController
        vc.flag = 2
        let cvc = getCurrentVc()
        cvc.navigationController?.pushViewController(vc,animated: true)
     
    }
    
    @objc func rightClick() {
        let vc = HotelHomeController()
        let cvc = getCurrentVc()
        cvc.navigationController?.pushViewController(vc, animated: true)
     
    }
}

extension TrainTicketHomeController:JXBannerDataSource,JXBannerDelegate{
    
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return 3
    }
    
    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {
        return JXBannerCellRegister(type: nil,
                                    reuseIdentifier: "HomeBannerColl",
                                    nib: UINib(nibName: "HomeBannerColl", bundle: Bundle.main))
    }
    
    func jxBanner(_ banner: JXBannerType, cellForItemAt index: Int, cell: UICollectionViewCell) -> UICollectionViewCell {
        if let tempCell = cell as? HomeBannerColl {
//            if let array = self.banners {
//                let dic = array[index] as! Dictionary<String,Any>
//                tempCell.img.kf.setImage(with: URL.init(string: "\(dic["img"] ?? "")"))
//
//            }
            tempCell.img.image = UIImage.init(named: "图层59")
        }
        return cell
    }
    
    func jxBanner(_ banner: JXBannerType,
                  layoutParams: JXBannerLayoutParams)
        -> JXBannerLayoutParams {
        return layoutParams
            .itemSize(CGSize(width: SCREEN_WIDTH, height: 203))
    }
    
    func jxBanner(pageControl banner: JXBannerType, numberOfPages: Int, coverView: UIView, builder: JXBannerPageControlBuilder) -> JXBannerPageControlBuilder {
        let pageControl = JXPageControlScale()
        pageControl.contentMode = .bottomRight
        pageControl.activeSize = CGSize(width: 15, height: 6)
        pageControl.inactiveSize = CGSize(width: 6, height: 6)
        pageControl.activeColor = UIColor.white
        pageControl.inactiveColor = UIColor.white
        pageControl.columnSpacing = 0
        pageControl.isAnimation = true
        builder.pageControl = pageControl
        builder.layout = {
            pageControl.snp.makeConstraints { (maker) in
                maker.left.right.equalTo(coverView)
                maker.top.equalTo(coverView.snp.bottom).offset(-80)
                maker.height.equalTo(20)
            }
        }
        return builder
    }
    
    func jxBanner(_ banner: JXBannerType, params: JXBannerParams) -> JXBannerParams {
        return params.timeInterval(3)
    }
    
    func jxBanner(_ banner: JXBannerType,
                      didSelectItemAt index: Int) {
        
    }

}

extension TrainTicketHomeController:RadioTimeDelegate{
    func radioTimeClick(date: String, according: String, difference: String) {
        self.dataStr = date
        self.according = according
        self.difference = difference
        self.tabView.reloadData()
    }
   
    
}

extension TrainTicketHomeController:GuessLikeDelegate{
    func guessLikeClick(data: NSDictionary) {
        
    }
}

extension TrainTicketHomeController:SwitchAddressDelegate{
    func switchAddressClick(data: Dictionary<String, Any>, type: Int) {
        if type == 2 {
            self.startCity = "\(data["stationName"] ?? "")"
        }else if type == 3 {
            self.endCity = "\(data["stationName"] ?? "")"
        }
        self.switchAddressView.hide()
        self.switchAddressView.hideKeyboard()
        self.tabView.reloadData()
    }
    
}

extension TrainTicketHomeController:CLLocationManagerDelegate{
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
        self.locationManager.stopUpdatingLocation()
        //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
        let currentLocation = locations.last
        //获取当前所在的城市名
        let geocoder = CLGeocoder.init()
        if let current = currentLocation {
            //根据经纬度反向地理编译出地址信息
            geocoder.reverseGeocodeLocation(current) { array, error in
                if let locats = array {
                    if locats.count > 0 {
                        let placemark = locats[0]
                        //获取城市
                        self.currCity = placemark.locality ?? ""
                        if self.currCity.isEmpty == true{
                            //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                            self.currCity = placemark.administrativeArea ?? ""
                        }
//                        self.chooseCity = self.currCity
                        self.tabView.reloadData()
                        self.getCityIdByName(country: placemark.country ?? "", province: placemark.administrativeArea ?? "", city: self.currCity, district: placemark.subLocality ?? "")
                    }
                }
            }
        }
        
        
    }
    
    //根据城市名称获取城市id接口
    func getCityIdByName(country:String,province:String,city:String,district:String) {
         NetWorkRequest(API1.getCityIdByName(parameters: ["country":country,"province":province,"city":city,"district":district]), completion: {[weak self] (responseString) -> (Void) in
       
            self?.cityId = responseString["data"]["cityId"].stringValue
         
            self?.tabView.header?.startRefreshing()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
}
